<template>
    <div>
        <!-- 引入三级下拉菜单 -->
        <!-- 将scene传递给子组件 -->
        <Category :scene="scene"></Category>
        <!-- 四列表格 -->
        <el-card style="margin: 10px 0px;">
            <div v-show="scene == 0">
                <el-button type="primary" size="default" @click="addAttr" icon="plus"
                    :disabled="!CategoryStore.c3id">添加属性</el-button>
                <el-table border style="margin: 10px 0px;" :data="AttrArr">
                    <el-table-column label="序号" type="index" align="center" width="80px">
                    </el-table-column>
                    <el-table-column label="属性名称" width="120px" prop="attrName">
                    </el-table-column>
                    <el-table-column label="属性值名称">
                        <template #="{ row, $index }">
                            <el-tag style="margin: 5px;" v-for="(item, index) in row.attrValueList" :key="item.id">{{
                                item.valueName }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="150px">
                        <template #="{ row, $index }">
                            <!-- 修改已有属性的按钮 confirm点击确认按钮触发的事件 -->
                            <el-button type="primary" size="small" icon="Edit" @click="updateAttr(row)"></el-button>
                            <el-popconfirm :title="`你确定删除${row.attrName}?`" @confirm="deleteAttr(row.id)">
                                <template #reference>
                                    <el-button type="primary" size="small" icon="Delete"></el-button>
                                </template>
                            </el-popconfirm>


                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-show="scene == 1">
                <el-form :inline="true">
                    <el-form-item label="属性名称">
                        <el-input placeholder="请输入属性名称" v-model="attrParams.attrName"></el-input>
                    </el-form-item>
                </el-form>
                <el-button type="primary" size="default" @click="addAttrValue" icon="Plus"
                    :disabled="attrParams.attrName ? false : true">添加属性值</el-button>
                <el-button type="primary" size="default" @click="cancel">取消</el-button>
                <el-table border style="margin: 10px 0px;" :data="attrParams.attrValueList">
                    <el-table-column label="序号" type="index" width="80px" align="center"></el-table-column>
                    <el-table-column label="属性值名称">
                        <template #="{ row, $index }">
                            <!-- row:即为当前属性值对象 -->
                            <el-input :ref="(vc: any) => inputArr[$index] = vc" v-if="row.flag"
                                @blur="tolook(row, $index)" size="small" v-model="row.valueName"
                                placeholder="请输入属性值的名称"></el-input>
                            <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="属性值操作">
                        <template #="{ row, $index }">
                            <el-button type="primary" size="small" @click="attrParams.attrValueList.splice($index, 1);"
                                icon="Delete"></el-button>

                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" size="default" @click="save"
                    :disabled="attrParams.attrValueList.length > 0 ? false : true">保存</el-button>
                <el-button type="primary" size="default" @click="cancel">取消</el-button>

            </div>

        </el-card>
    </div>
</template>

<script setup lang="ts">
// 组合式APi函数watch
import { watch, ref, reactive, nextTick ,onBeforeUnmount} from 'vue';
// 引入获取已有属性与属性值的接口
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr';
import useCategoryStore from '@/store/modules/category';
import type { AttrResponseDate, Attr, AttrValue } from '@/api/product/attr/type';
import { ElMessage } from 'element-plus';
let CategoryStore = useCategoryStore();
// 存储已有的属性和属性值
let AttrArr = ref<Attr[]>([]);
let scene = ref<number>(0);
// 收集新增的属性的数据
let attrParams = reactive<Attr>({
    attrName: "",//新增的属性的名字
    attrValueList: [],//新增的属性值数组
    categoryId: '',//三级分类id
    categoryLevel: 3,//代表的是三级分类
});
//收集input表单，实现自动聚焦
let inputArr = ref<any>([]);
// 监听仓库三级分类ID的变化
watch(() => CategoryStore.c3id, () => {
    // 清空上一次查询的属性和属性值
    AttrArr.value = [];
    // 保证三级分类得有才能发请求
    if (!CategoryStore.c3id) return;
    getAttr();
});
// 获取已有属性和属性值函数、
const getAttr = async () => {
    // 获取分类ID
    const { c1id, c2id, c3id } = CategoryStore;
    let result: AttrResponseDate = await reqAttr(c1id, c2id, c3id);
    if (result.code == 200) {
        AttrArr.value = result.data;
    }

}
// 添加属性的按钮绑定的函数

const addAttr = () => {
    // 每一次点击的时候先清空数据
    // es6新增方法
    Object.assign(attrParams, {
        attrName: "",//新增的属性的名字
        attrValueList: [],//新增的属性值数组
        categoryId: CategoryStore.c3id,//三级分类id
        categoryLevel: 3,//代表的是三级分类
    })
    scene.value = 1;
}
// 修改属性
const updateAttr = (row: Attr) => {
    scene.value = 1;
    // 将row的值拷贝给attParams  方法：Object.assign() 浅拷贝指向同一地址，修改一项对应的一项也会被修改
    // JSON.parse(JSON.stringify(row))深拷贝
    Object.assign(attrParams, JSON.parse(JSON.stringify(row)));
}
// 取消修改属性按钮
const cancel = () => {
    scene.value = 0;
}
// 添加属性值按钮的回调
const addAttrValue = () => {
    attrParams.attrValueList.push({
        valueName: '',
        flag: true,//控制属性值编辑模式切换
    })
    // 点击添加属性值的按钮的时候，向数组添加一个属性值对象
    // 数组最后一个表单聚焦
    nextTick(() => {
        inputArr.value[attrParams.attrValueList.length - 1].focus();
    })
}
// 保存按钮的回调函数
const save = async () => {
    let result: any = await reqAddOrUpdateAttr(attrParams);

    // 切换页面
    if (result.code == 200) {
        scene.value = 0;
        // 提示信息
        ElMessage({
            type: 'success',
            message: attrParams.id ? '修改成功' : '添加成功'
        });
        //获取全部已有的属性与属性值
        getAttr()
    } else {
        ElMessage({
            type: 'error',
            message: attrParams.id ? '修改失败' : '添加失败'
        })
    }
}
// 属性值输入框失去焦点
//属性值表单元素失却焦点事件回调
const tolook = (row: AttrValue, $index: number) => {

    //非法情况判断1
    if (row.valueName.trim() == '') {
        //删除调用对应属性值为空的元素
        attrParams.attrValueList.splice($index, 1);
        //提示信息
        ElMessage({
            type: 'error',
            message: '属性值不能为空'
        })
        return;
    }
    //非法情况2
    let repeat = attrParams.attrValueList.find((item) => {
        //切记把当前失却焦点属性值对象从当前数组扣除判断
        if (item != row) {
            return item.valueName === row.valueName;
        }
    });

    if (repeat) {
        //将重复的属性值从数组当中干掉
        attrParams.attrValueList.splice($index, 1);
        //提示信息
        ElMessage({
            type: 'error',
            message: '属性值不能重复'
        })
        return;
    }
    //相应的属性值对象flag:变为false,展示div
    row.flag = false;
}

const toEdit = (row: AttrValue, $index: number) => {
    row.flag = true;
    //    nextTick:响应式数据发生变化，获取更新的DOM（组件实例
    nextTick(() => {
        inputArr.value[$index].focus();
    })
}
// 删除属性的回调函数
const deleteAttr = async (attrId: number) => {
    let result: any = await reqRemoveAttr(attrId);
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: '删除成功'
        })
        // 再次获取数据
        getAttr();
    } else {
        ElMessage({
            type: 'error',
            message: '删除失败'
        })

    }
}

// 路由组件销毁时调用的函数——把三级分类数据清空
onBeforeUnmount(()=>{
    // 清空仓库的数据:$reste()
    CategoryStore.$reset()
})
</script>

<style scoped></style>